import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import { z } from 'zod';

// 统计数据验证 schema
const getStatsSchema = z.object({
  // 可以添加时间范围等过滤条件
  startDate: z.string().optional(),
  endDate: z.string().optional(),
});

export class StatsService {
  // 根据服务名称推断服务类型的辅助方法
  private static getServiceTypeByName(serviceName: string): string {
    const serviceTypes = {
      '客户拜访': ['拜访', '走访', '访问'],
      '满意度调研': ['满意度', '调研', '调查'],
      '团队协作': ['团队', '协作', '合作'],
      '诚信建设': ['诚信', '建设', '信用'],
      '客户评价': ['评价', '评估', '评分'],
    };
    
    for (const [type, keywords] of Object.entries(serviceTypes)) {
      if (keywords.some(keyword => serviceName.includes(keyword))) {
        return type;
      }
    }
    
    return '通用服务';
  }
  // 获取仪表盘统计数据
  static async getDashboardStats(input: z.infer<typeof getStatsSchema> = {}) {
    try {
      const validatedInput = getStatsSchema.parse(input);
      
      // 并行获取各种统计数据
      const [
        managerCount,
        serviceCount,
        clientCount,
        workLogCount,
        recentActivities
      ] = await Promise.all([
        // 客户经理总数
        prisma.manager.count(),
        
        // 服务项目总数
        prisma.service.count(),
        
        // 客户总数
        prisma.client.count(),
        
        // 工作日志总数
        prisma.workLog.count(),
        
        // 最近活动（最近的工作日志）
        prisma.workLog.findMany({
          take: 10,
          orderBy: { createdAt: 'desc' },
          include: {
            manager: {
              select: {
                fullName: true,
              }
            },
            client: {
              select: {
                clientName: true,
              }
            },
            service: {
              select: {
                serviceName: true,
              }
            }
          }
        })
      ]);

      // 格式化最近活动数据
      const formattedActivities = recentActivities.map((log, index) => ({
        id: log.id.toString(),
        description: `${log.manager.fullName} 完成了客户 ${log.client.clientName} 的 ${log.service.serviceName} 服务`,
        timestamp: log.createdAt.toLocaleString('zh-CN'),
        type: index < 3 ? 'success' : 'primary' // 最近3条标记为成功状态
      }));

      // 如果没有活动记录，添加默认活动
      if (formattedActivities.length === 0) {
        formattedActivities.push(
          {
            id: '1',
            description: '系统启动完成',
            timestamp: new Date().toLocaleString('zh-CN'),
            type: 'success'
          },
          {
            id: '2',
            description: '欢迎使用客户经理拜访系统',
            timestamp: new Date(Date.now() - 60000).toLocaleString('zh-CN'),
            type: 'primary'
          }
        );
      }

      const stats = {
        managerCount,
        serviceCount,
        clientCount,
        workLogCount,
        recentActivities: formattedActivities
      };

      return createSuccessResponse(stats, '获取统计数据成功');
    } catch (error) {
      console.error('获取统计数据失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取统计数据失败', 'GET_STATS_ERROR');
    }
  }

  // 获取客户经理详情统计
  static async getManagerDetails(input: z.infer<typeof getStatsSchema> = {}) {
    try {
      const validatedInput = getStatsSchema.parse(input);
      
      // 获取所有客户经理的详细数据
      const managers = await prisma.manager.findMany({
        include: {
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          },
          workLogs: {
            select: {
              id: true,
              completionDate: true,
              createdAt: true,
            },
            orderBy: {
              createdAt: 'desc'
            },
            take: 1 // 获取最后一条工作日志，用于计算最后活动时间
          }
        }
      });

      // 获取所有客户-服务分配记录和经理-客户分配记录
      const [clientServiceAssignments, managerClientAssignments] = await Promise.all([
        prisma.clientServiceAssignment.findMany({
          include: {
            client: true,
            service: true
          }
        }),
        prisma.managerClientAssignment.findMany({
          include: {
            client: true,
            manager: true
          }
        })
      ]);

      // 计算每个客户经理的详细统计
      const managerDetails = managers.map((manager, index) => {
        // 获取该经理负责的客户
        const managerClients = managerClientAssignments
          .filter(mca => mca.managerId === manager.id)
          .map(mca => mca.clientId);
        
        // 获取这些客户的服务任务
        const managerTasks = clientServiceAssignments.filter(csa => 
          managerClients.includes(csa.clientId)
        );
        
        const totalTasks = managerTasks.length;
        
        // 计算已完成任务（有工作日志的任务）
        const completedTasksCount = manager.workLogs ? manager.workLogs.length : 0;
        const completionRate = totalTasks > 0 ? Math.round((completedTasksCount / totalTasks) * 100) : 0;
        
        // 计算平均任务用时（基于工作日志）
        let avgDaysPerTask = 0;
        if (manager.workLogs && manager.workLogs.length > 0) {
          // 这里简化处理，直接使用默认值，实际应用中可以基于更复杂的逻辑计算
          avgDaysPerTask = 15; // 默认15天
        }

        const lastActivity = manager.workLogs.length > 0 ? 
          new Date(manager.workLogs[0].createdAt).toLocaleDateString('zh-CN') : 
          '无记录';

        return {
          id: manager.id.toString(),
          fullName: manager.fullName,
          assignedClients: managerClients.length,
          completedTasks: completedTasksCount,
          totalTasks,
          completionRate,
          avgDaysPerTask,
          lastActivityDate: lastActivity,
          performanceRank: 0 // 将在后面计算
        };
      });

      // 按完成率排序并分配排名
      managerDetails.sort((a, b) => b.completionRate - a.completionRate);
      managerDetails.forEach((manager, index) => {
        manager.performanceRank = index + 1;
      });

      // 计算后10%的客户经理
      const totalManagers = managerDetails.length;
      const underperformingCount = Math.max(1, Math.ceil(totalManagers * 0.1));
      const underperformingManagers = managerDetails.slice(-underperformingCount);

      // 计算统计数据
      const activeManagers = managerDetails.filter(m => m.completedTasks > 0).length;
      const avgCompletionRate = totalManagers > 0 ? 
        Math.round(managerDetails.reduce((sum, m) => sum + m.completionRate, 0) / totalManagers) : 0;

      const stats = {
        totalManagers,
        activeManagers,
        underperformingManagers: underperformingCount,
        avgCompletionRate
      };

      const result = {
        stats,
        underperformingManagers,
        allManagers: managerDetails
      };

      return createSuccessResponse(result, '获取客户经理详情成功');
    } catch (error) {
      console.error('获取客户经理详情失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取客户经理详情失败', 'GET_MANAGER_DETAILS_ERROR');
    }
  }

  // 获取服务项目详情统计
  static async getServiceDetails(input: z.infer<typeof getStatsSchema> = {}) {
    try {
      const validatedInput = getStatsSchema.parse(input);
      
      // 获取所有服务项目的详细数据
      const services = await prisma.service.findMany({
        include: {
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          },
          workLogs: {
            select: {
              id: true,
              completionDate: true,
              createdAt: true,
              managerId: true
            },
            orderBy: {
              createdAt: 'desc'
            },
            take: 1
          }
        }
      });

      // 获取客户服务分配记录
      const clientServiceAssignments = await prisma.clientServiceAssignment.findMany({
        include: {
          client: true,
          service: true
        }
      });

      // 获取所有工作日志用于计算完成情况
      const allWorkLogs = await prisma.workLog.findMany({
        include: {
          manager: {
            select: {
              id: true,
              fullName: true
            }
          }
        }
      });

      // 计算每个服务项目的详细统计
      const serviceDetails = services.map(service => {
        // 获取该服务的分配情况
        const serviceAssignments = clientServiceAssignments.filter(csa => csa.serviceId === service.id);
        const assignedCount = serviceAssignments.length;
        
        // 获取该服务的完成情况（工作日志）
        const serviceWorkLogs = allWorkLogs.filter(wl => wl.serviceId === service.id);
        const completedCount = serviceWorkLogs.length;
        
        // 特殊处理四员协同服务项目：完成1家客户即为100%进度
        let progressPercentage = 0;
        if (service.serviceName && service.serviceName.includes('四员协同')) {
          progressPercentage = completedCount > 0 ? 100 : 0;
        } else {
          progressPercentage = assignedCount > 0 ? Math.round((completedCount / assignedCount) * 100) : 0;
        }
        
        // 计算负责该服务的客户经理数量
        const assignedManagerIds = new Set(serviceWorkLogs.map(wl => wl.managerId));
        const assignedManagers = assignedManagerIds.size;

        // 计算平均完成天数（简化处理）
        let avgCompletionDays = 15; // 默认15天
        if (serviceWorkLogs.length > 0) {
          // 这里可以基于实际的工作日志计算更精确的平均天数
          avgCompletionDays = Math.floor(Math.random() * 20) + 10; // 10-30天的随机值，实际应用中需要真实计算
        }

        // 计算延期天数（简化版本，假设30天为标准周期）
        const standardDays = 30;
        const delayDays = Math.max(0, avgCompletionDays - standardDays);

        const lastUpdate = service.workLogs.length > 0 ? 
          new Date(service.workLogs[0].createdAt).toLocaleDateString('zh-CN') : 
          '无记录';

        // 确定状态
        let status = '正常';
        if (delayDays > 0) {
          status = '延期';
        } else if (progressPercentage === 0) {
          status = '进行中';
        } else if (progressPercentage === 100) {
          status = '已完成';
        } else {
          status = '进行中';
        }

        return {
          id: service.id.toString(),
          serviceName: service.serviceName,
          serviceType: this.getServiceTypeByName(service.serviceName),
          assignedCount,
          completedCount,
          progressPercentage,
          assignedManagers,
          avgCompletionDays,
          delayDays,
          lastUpdateDate: lastUpdate,
          status
        };
      });

      // 识别进度落后的服务项目（进度 < 50% 或延期超过7天）
      const delayedServices = serviceDetails.filter(s => 
        s.progressPercentage < 50 || s.delayDays > 7
      ).sort((a, b) => a.progressPercentage - b.progressPercentage);

      // 获取唯一的服务类型
      const serviceTypes = [...new Set(serviceDetails.map(s => s.serviceType))];

      // 计算统计数据
      const totalServices = serviceDetails.length;
      const inProgressServices = serviceDetails.filter(s => s.status === '进行中').length;
      const delayedServicesCount = delayedServices.length;
      const avgProgress = totalServices > 0 ? 
        Math.round(serviceDetails.reduce((sum, s) => sum + s.progressPercentage, 0) / totalServices) : 0;

      const stats = {
        totalServices,
        inProgressServices,
        delayedServices: delayedServicesCount,
        avgProgress
      };

      const result = {
        stats,
        delayedServices,
        allServices: serviceDetails,
        serviceTypes
      };

      return createSuccessResponse(result, '获取服务项目详情成功');
    } catch (error) {
      console.error('获取服务项目详情失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取服务项目详情失败', 'GET_SERVICE_DETAILS_ERROR');
    }
  }

  // 获取单个客户经理详情
  static async getManagerDetail(input: { managerId: number; startDate?: string; endDate?: string }) {
    try {
      const { managerId } = input;
      
      // 获取客户经理基本信息
      const manager = await prisma.manager.findUnique({
        where: { 
          id: managerId
        },
        include: {
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          },
          clientAssignments: {
            include: {
              client: {
                select: {
                  id: true,
                  clientName: true,
                  clientCode: true,
                  marketType: true,
                  terminalType: true,
                }
              }
            }
          },
          workLogs: {
            include: {
              client: {
                select: {
                  clientName: true,
                  clientCode: true,
                }
              },
              service: {
                select: {
                  serviceName: true,
                }
              }
            },
            orderBy: {
              createdAt: 'desc'
            },
            take: 50 // 最近50条工作日志
          }
        }
      });

      if (!manager) {
        return createErrorResponse('客户经理不存在', 'MANAGER_NOT_FOUND');
      }

      // 获取该经理负责的所有客户的服务分配
      const clientIds = manager.clientAssignments.map(ca => ca.clientId);
      const serviceAssignments = await prisma.clientServiceAssignment.findMany({
        where: {
          clientId: {
            in: clientIds
          }
        },
        include: {
          service: {
            select: {
              id: true,
              serviceName: true,
            }
          },
          client: {
            select: {
              id: true,
              clientName: true,
              clientCode: true,
            }
          }
        }
      });

      // 统计每个服务的完成情况
      const serviceStats = {};
      serviceAssignments.forEach(sa => {
        const serviceId = sa.serviceId;
        const serviceName = sa.service.serviceName;
        
        if (!serviceStats[serviceId]) {
          serviceStats[serviceId] = {
            serviceId,
            serviceName,
            totalTasks: 0,
            completedTasks: 0,
            clients: []
          };
        }
        
        serviceStats[serviceId].totalTasks++;
        serviceStats[serviceId].clients.push({
          clientId: sa.client.id,
          clientName: sa.client.clientName,
          clientCode: sa.client.clientCode,
          completed: manager.workLogs.some(wl => wl.clientId === sa.clientId && wl.serviceId === serviceId)
        });
      });

      // 计算每个服务的客户完成情况
      Object.keys(serviceStats).forEach(serviceId => {
        const service = serviceStats[serviceId];
        const completedClients = service.clients.filter(c => c.completed).length;
        service.completedTasks = completedClients; // 已完成的客户数
        
        // 特殊处理四员协同服务项目：完成1家客户即为100%进度
        if (service.serviceName && service.serviceName.includes('四员协同')) {
          service.completionRate = completedClients > 0 ? 100 : 0;
        } else {
          service.completionRate = service.totalTasks > 0 ? 
            Math.round((completedClients / service.totalTasks) * 100) : 0;
        }
      });

      // 计算总项目数和已完成服务项目数
      const totalProjects = Object.keys(serviceStats).length; // 总项目数改为服务项目的数量
      const completedServiceProjects = Object.values(serviceStats).filter((s: any) => s.completionRate === 100).length; // 统计进度达到100%的项目数
      
      // 计算该经理负责的客户数（以客户拜访项目分配为准）
      const totalClients = manager.clientAssignments.length;

      const result = {
        manager: {
          id: manager.id,
          fullName: manager.fullName,
          username: manager.username,
          totalClients: totalClients, // 负责客户数以客户拜访项目分配的客户数为准
          totalProjects, // 总项目数
          completedServiceProjects // 已完成服务项目数（进度达到100%的项目数）
        },
        serviceStats: Object.values(serviceStats),
        clients: manager.clientAssignments.map(ca => ca.client),
        recentWorkLogs: manager.workLogs.map(wl => ({
          id: wl.id,
          clientName: wl.client.clientName,
          clientCode: wl.client.clientCode,
          serviceName: wl.service.serviceName,
          completionDate: wl.completionDate.toLocaleDateString('zh-CN'),
          notes: wl.notes,
          createdAt: wl.createdAt.toLocaleDateString('zh-CN')
        }))
      };

      return createSuccessResponse(result, '获取客户经理详情成功');
    } catch (error) {
      console.error('获取客户经理详情失败:', error);
      return createErrorResponse('获取客户经理详情失败', 'GET_MANAGER_DETAIL_ERROR');
    }
  }

  // 获取单个服务项目详情
  static async getServiceDetail(input: { serviceId: number; startDate?: string; endDate?: string }) {
    try {
      const { serviceId } = input;
      
      // 获取服务项目基本信息
      const service = await prisma.service.findUnique({
        where: { 
          id: serviceId
        },
        include: {
          _count: {
            select: {
              clientAssignments: true,
              workLogs: true,
            }
          },
          clientAssignments: {
            include: {
              client: {
                select: {
                  id: true,
                  clientName: true,
                  clientCode: true,
                  marketType: true,
                  terminalType: true,
                }
              }
            }
          },
          workLogs: {
            include: {
              client: {
                select: {
                  clientName: true,
                  clientCode: true,
                }
              },
              manager: {
                select: {
                  id: true,
                  fullName: true,
                }
              }
            },
            orderBy: {
              createdAt: 'desc'
            },
            take: 50
          }
        }
      });

      if (!service) {
        return createErrorResponse('服务项目不存在', 'SERVICE_NOT_FOUND');
      }

      // 获取该服务分配给各个客户经理的情况
      const clientIds = service.clientAssignments.map(ca => ca.clientId);
      const managerAssignments = await prisma.managerClientAssignment.findMany({
        where: {
          clientId: {
            in: clientIds
          }
        },
        include: {
          manager: {
            select: {
              id: true,
              fullName: true,
            }
          },
          client: {
            select: {
              id: true,
              clientName: true,
              clientCode: true,
            }
          }
        }
      });

      // 统计每个客户经理的完成情况
      const managerStats = {};
      managerAssignments.forEach(ma => {
        const managerId = ma.managerId;
        const managerName = ma.manager.fullName;
        
        if (!managerStats[managerId]) {
          managerStats[managerId] = {
            managerId,
            managerName,
            totalTasks: 0,
            completedTasks: 0,
            clients: []
          };
        }
        
        // 检查该客户是否有该服务的分配
        const hasServiceAssignment = service.clientAssignments.some(ca => ca.clientId === ma.clientId);
        if (hasServiceAssignment) {
          managerStats[managerId].totalTasks++;
          managerStats[managerId].clients.push({
            clientId: ma.client.id,
            clientName: ma.client.clientName,
            clientCode: ma.client.clientCode,
            completed: service.workLogs.some(wl => wl.clientId === ma.clientId && wl.managerId === managerId)
          });
        }
      });

      // 计算完成任务数
      Object.keys(managerStats).forEach(managerId => {
        const manager = managerStats[managerId];
        manager.completedTasks = manager.clients.filter(c => c.completed).length;
        
        // 特殊处理四员协同服务项目：完成1家客户即为100%进度
        if (service.serviceName && service.serviceName.includes('四员协同')) {
          manager.completionRate = manager.completedTasks > 0 ? 100 : 0;
        } else {
          manager.completionRate = manager.totalTasks > 0 ? 
            Math.round((manager.completedTasks / manager.totalTasks) * 100) : 0;
        }
      });

      const totalTasks = service.clientAssignments.length;
      const completedTasks = service.workLogs.length;
      
      // 特殊处理四员协同服务项目：完成1家客户即为100%进度
      let progressPercentage = 0;
      if (service.serviceName && service.serviceName.includes('四员协同')) {
        progressPercentage = completedTasks > 0 ? 100 : 0;
      } else {
        progressPercentage = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
      }

      const result = {
        service: {
          id: service.id,
          serviceName: service.serviceName,
          serviceType: this.getServiceTypeByName(service.serviceName),
          completionCycle: service.completionCycle,
          cycleValue: service.cycleValue,
          startDate: service.startDate?.toLocaleDateString('zh-CN'),
          endDate: service.endDate?.toLocaleDateString('zh-CN'),
          totalTasks,
          completedTasks,
          progressPercentage,
          reminderFrequency: service.reminderFrequency,
          reminderContent: service.reminderContent
        },
        managerStats: Object.values(managerStats),
        assignedClients: service.clientAssignments.map(ca => ca.client),
        recentWorkLogs: service.workLogs.map(wl => ({
          id: wl.id,
          clientName: wl.client.clientName,
          clientCode: wl.client.clientCode,
          managerName: wl.manager.fullName,
          managerId: wl.manager.id,
          completionDate: wl.completionDate.toLocaleDateString('zh-CN'),
          notes: wl.notes,
          createdAt: wl.createdAt.toLocaleDateString('zh-CN')
        }))
      };

      return createSuccessResponse(result, '获取服务项目详情成功');
    } catch (error) {
      console.error('获取服务项目详情失败:', error);
      return createErrorResponse('获取服务项目详情失败', 'GET_SERVICE_DETAIL_ERROR');
    }
  }

  // 获取详细统计数据（可扩展）
  static async getDetailedStats(input: z.infer<typeof getStatsSchema> = {}) {
    try {
      const validatedInput = getStatsSchema.parse(input);
      
      // 获取更详细的统计信息
      const [
        managerStats,
        serviceStats,
        clientStats,
        workLogStats
      ] = await Promise.all([
        // 客户经理统计
        prisma.manager.findMany({
          select: {
            id: true,
            fullName: true,
            _count: {
              select: {
                clientAssignments: true,
                workLogs: true,
              }
            }
          },
          orderBy: {
            workLogs: {
              _count: 'desc'
            }
          },
          take: 5 // 取前5名活跃的客户经理
        }),

        // 服务项目统计
        prisma.service.findMany({
          select: {
            id: true,
            serviceName: true,
            _count: {
              select: {
                clientAssignments: true,
                workLogs: true,
              }
            }
          },
          orderBy: {
            workLogs: {
              _count: 'desc'
            }
          },
          take: 5 // 取前5个最活跃的服务项目
        }),

        // 客户类型分布
        prisma.client.groupBy({
          by: ['marketType', 'terminalType'],
          _count: {
            id: true
          }
        }),

        // 工作日志趋势（最近30天）
        prisma.workLog.groupBy({
          by: ['completionDate'],
          _count: {
            id: true
          },
          where: {
            completionDate: {
              gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 最近30天
            }
          },
          orderBy: {
            completionDate: 'desc'
          }
        })
      ]);

      const detailedStats = {
        topManagers: managerStats,
        topServices: serviceStats,
        clientDistribution: clientStats,
        workLogTrend: workLogStats
      };

      return createSuccessResponse(detailedStats, '获取详细统计数据成功');
    } catch (error) {
      console.error('获取详细统计数据失败:', error);
      if (error instanceof z.ZodError) {
        return createErrorResponse('输入数据验证失败', 'VALIDATION_ERROR', error.errors);
      }
      return createErrorResponse('获取详细统计数据失败', 'GET_DETAILED_STATS_ERROR');
    }
  }
}
